import java.util.concurrent.Semaphore;

public class CyclicBarrierNew {
	private int parties;
	//keeps track of balls which have reached the barrier
	private int numReached;
	//a mutex semaphore. A semaphore to make sure that
	//only one process/ball may read and update the numReached
	private Semaphore incNumReached;
	//a semaphore for which all the processes block
	private Semaphore barrierSem;
	
	public CyclicBarrierNew(int parties){
		this.parties = parties;
		this.numReached = 0;
		this.incNumReached = new Semaphore(1);
		this.barrierSem = new Semaphore(0);
	}
	
	public void await(){
		try {
			incNumReached.acquire();
			//if(incNumReached.tryAcquire()){
				//The process/ball has reached the barrier, update the number
				//of reached processes/balls
				numReached++;
				//if all processes/balls have reached the barrier, release the 
				//barrierSem. This will allow a blocked process/frozen ball to move again.
				if(numReached >= parties){
					this.barrierSem.release();
					this.barrierSem.release();
					this.barrierSem.release();
					this.barrierSem.release();
					//reset the number of processes that have reached the barrier
					this.numReached = 0;
					
				}
				incNumReached.release();
	
		//	}

		
			this.barrierSem.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
